

<?php

class TypeController extends Zend_Controller_Action {

    public function preDispatch() {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            if ($this->_request->getActionName() != 'admin') {
                $this->_redirect('admin');
            }
        }
    }

    public function indexAction() {
        $this->buildHead();
        $type = new Model_Type();
        $data = $type->getAllType();
        $this->view->type = $data;
    }

    public function addAction() {
        $name = $this->_request->getParam("name");
        $this->_helper->viewRenderer->setNoRender(true);
        $type = new Model_Type();
        $result = $type->insertNewType($name);
        if ($result != null) {
            echo $this->returnDone();
        } else {
            echo $this->returnFail();
        }
    }

    public function deleteAction() {
        $id = $this->_request->getParam("id");
        $this->_helper->viewRenderer->setNoRender(true);
        $type = new Model_Type();
        $result = $type->deleteType($id);
        if ($result != null) {
            echo $this->returnDone();
        } else {
            echo $this->returnFail();
        }
    }

    public function updateAction() {
        $id = $this->_request->getParam("id");
        $name = $this->_request->getParam("name");
        $this->_helper->viewRenderer->setNoRender(true);
        $type = new Model_Type();
        $result = $type->updateType($id, $name);
        if ($result != null) {
            echo $this->returnDone();
        } else {
            echo $this->returnFail();
        }
    }

    private function returnDone() {
        $array = array(
            "errorCode" => 0,
            "errorMessage" => "Query completed.",
        );
        return json_encode($array);
    }

    private function returnFail() {
        $array = array(
            "errorCode" => -1,
            "errorMessage" => "Query fail.",
        );
        return json_encode($array);
    }

    private function buildHead() {
        $base = $this->_request->getBaseUrl();
        $this->view->base = $base;
        $this->view->update = $base . "/type/update";
        $this->view->delete = $base . "/type/delete";
        $this->view->add = $base . "/type/add";
        $this->view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
        $this->view->headScript()->appendFile($base . "/js/Ajax.js", 'text/javascript');
        $this->view->headScript()->appendFile($base . "/js/sunnyAjax.js", 'text/javascript');
    }

}
?>

